use eframe::egui::{self, CentralPanel, Visuals};
use egui_plotter::EguiBackend;
use plotters::{coord::ReverseCoordTranslate, prelude::*};

fn main() {
    let native_options = eframe::NativeOptions::default();
    eframe::run_native(
        "Simple Example",
        native_options,
        Box::new(|cc| Ok(Box::new(Eguiplotterdemo::new(cc)))),
    )
    .unwrap();
}

struct Eguiplotterdemo {}

impl Eguiplotterdemo {
    fn new(cc: &eframe::CreationContext<'_>) -> Self {
        // Disable feathering as it causes artifacts
        let context = &cc.egui_ctx;

        context.tessellation_options_mut(|tess_options| {
            tess_options.feathering = false;
        });

        // Also enable light mode
        context.set_visuals(Visuals::light());

        Self {}
    }
}

impl eframe::App for Eguiplotterdemo {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        CentralPanel::default().show(ctx, |ui| {
            let root = EguiBackend::new(ui).into_drawing_area();
            root.fill(&BLUE).unwrap();
            let mut chart = ChartBuilder::on(&root)
                .caption("caption", ("sans-serif", 40).into_font())
                .margin(50)
                .x_label_area_size(30)
                .y_label_area_size(30)
                .build_cartesian_2d(-1f64..1f64, -0.1f64..1f64)
                .unwrap();

            chart.configure_mesh().draw().unwrap();

            chart
                .draw_series(LineSeries::new(
                    (-50..=50).map(|x| x as f64 / 50.0).map(|x| (x, x * x)),
                    &RED,
                ))
                .unwrap();

            if let Some(pos) = ui.input(|i| i.pointer.hover_pos()) {
                println!("{}", pos);
                let pos = pos - ui.min_rect().min;
                if let Some(np) = chart
                    .as_coord_spec()
                    .reverse_translate((pos.x as i32, pos.y as i32))
                {
                    chart
                        .draw_series(PointSeries::of_element([np], 5, &RED, &|c, s, st| {
                            return EmptyElement::at(c)
                                + Circle::new((0, 0), s, st.filled())
                                + Text::new(
                                    format!("{:?}", c),
                                    (10, 0),
                                    ("sans-serif", 10).into_font(),
                                );
                        }))
                        .unwrap();
                }
            }

            root.present().unwrap();
        });
    }
}
